<template>
  <Sidebar :menu-items="menuItems" title="管理系统">
    <div class="flex-1 flex flex-col overflow-hidden">
      <!-- 顶部导航 -->
      <Header 
        :user-info="authStore.userInfo"
        @logout="handleLogout"
      />
      
      <!-- 主内容区 -->
      <main class="flex-1 overflow-x-hidden overflow-y-auto bg-gray-50 p-6">
        <div class="max-w-7xl mx-auto">
          <!-- 页面标题 -->
          <div class="mb-6">
            <h1 class="text-2xl font-bold text-gray-900">学生管理</h1>
            <p class="mt-1 text-sm text-gray-600">
              管理学生信息，包括新增、编辑、删除和查看学生详情
            </p>
          </div>

          <!-- 数据表格 -->
          <DataTable
            title="学生列表"
            :columns="columns"
            :data="students"
            :loading="loading"
            :selectable="true"
            @selection-change="handleSelectionChange"
            @sort="handleSort"
          >
            <!-- 工具栏 -->
            <template #toolbar>
              <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between space-y-4 sm:space-y-0">
                <!-- 搜索栏 -->
                <div class="flex-1">
                  <SearchBar
                    :filters="searchFilters"
                    search-placeholder="搜索学生姓名、学号..."
                    @search="handleSearch"
                  />
                </div>
                
                <!-- 操作按钮 -->
                <div class="flex items-center space-x-3">
                  <button
                    @click="showAddModal = true"
                    class="btn btn-primary"
                  >
                    <PlusIcon class="h-4 w-4 mr-2" />
                    新增学生
                  </button>
                  
                  <button
                    @click="showImportModal = true"
                    class="btn btn-secondary"
                  >
                    <DocumentArrowUpIcon class="h-4 w-4 mr-2" />
                    批量导入
                  </button>
                  
                  <button
                    @click="exportStudents"
                    class="btn btn-secondary"
                    :disabled="selectedRows.length === 0"
                  >
                    <DocumentArrowDownIcon class="h-4 w-4 mr-2" />
                    导出选中
                  </button>
                </div>
              </div>
            </template>

            <!-- 自定义列 -->
            <template #column-avatar="{ item }">
              <div class="flex items-center">
                <img 
                  class="h-8 w-8 rounded-full bg-gray-300" 
                  :src="item.avatar || '/default-avatar.png'"
                  :alt="item.name"
                >
              </div>
            </template>

            <template #column-registrationStatus="{ item }">
              <StatusTag 
                :status="item.registrationStatus"
                :text="getRegistrationStatusText(item.registrationStatus)"
              />
            </template>

            <template #column-paymentStatus="{ item }">
              <StatusTag 
                :status="item.paymentStatus"
                :text="getPaymentStatusText(item.paymentStatus)"
              />
            </template>

            <!-- 操作列 -->
            <template #actions="{ item }">
              <div class="flex items-center space-x-2">
                <button
                  @click="viewStudent(item)"
                  class="text-blue-600 hover:text-blue-900 text-sm font-medium"
                >
                  查看
                </button>
                <button
                  @click="editStudent(item)"
                  class="text-indigo-600 hover:text-indigo-900 text-sm font-medium"
                >
                  编辑
                </button>
                <button
                  @click="deleteStudent(item)"
                  class="text-red-600 hover:text-red-900 text-sm font-medium"
                >
                  删除
                </button>
              </div>
            </template>
          </DataTable>
        </div>
      </main>
    </div>

    <!-- 新增/编辑学生弹窗 -->
    <StudentModal
      v-if="showAddModal || showEditModal"
      :visible="showAddModal || showEditModal"
      :student="currentStudent"
      :mode="showAddModal ? 'add' : 'edit'"
      @close="closeModal"
      @save="handleSaveStudent"
    />

    <!-- 学生详情弹窗 -->
    <StudentDetailModal
      v-if="showDetailModal"
      :visible="showDetailModal"
      :student="currentStudent"
      @close="showDetailModal = false"
    />

    <!-- 批量导入弹窗 -->
    <ImportModal
      v-if="showImportModal"
      :visible="showImportModal"
      @close="showImportModal = false"
      @import="handleImport"
    />
  </Sidebar>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore, useAdminStore } from '../../stores'
import { getRegistrationStatus, getPaymentStatus } from '../../utils'
import Sidebar from '../../components/common/Sidebar.vue'
import Header from '../../components/common/Header.vue'
import DataTable from '../../components/common/DataTable.vue'
import SearchBar from '../../components/common/SearchBar.vue'
import StatusTag from '../../components/common/StatusTag.vue'
import {
  HomeIcon,
  UserGroupIcon,
  AcademicCapIcon,
  BuildingOfficeIcon,
  BuildingOffice2Icon,
  ClipboardDocumentCheckIcon,
  CurrencyDollarIcon,
  MegaphoneIcon,
  PlusIcon,
  DocumentArrowUpIcon,
  DocumentArrowDownIcon
} from '@heroicons/vue/24/outline'

const router = useRouter()
const authStore = useAuthStore()
const adminStore = useAdminStore()

// 菜单配置
const menuItems = [
  { name: '首页', path: '/admin/dashboard', icon: HomeIcon },
  { name: '学生管理', path: '/admin/students', icon: UserGroupIcon },
  { name: '专业管理', path: '/admin/majors', icon: AcademicCapIcon },
  { name: '班级管理', path: '/admin/classes', icon: BuildingOfficeIcon },
  { name: '宿舍管理', path: '/admin/dormitory', icon: BuildingOffice2Icon },
  { name: '报到管理', path: '/admin/registration', icon: ClipboardDocumentCheckIcon },
  { name: '财务管理', path: '/admin/finance', icon: CurrencyDollarIcon },
  { name: '通知公告', path: '/admin/notices', icon: MegaphoneIcon }
]

// 表格列配置
const columns = [
  { key: 'avatar', title: '头像', sortable: false },
  { key: 'studentId', title: '学号', sortable: true },
  { key: 'name', title: '姓名', sortable: true },
  { key: 'gender', title: '性别', sortable: false },
  { key: 'major', title: '专业', sortable: true },
  { key: 'class', title: '班级', sortable: true },
  { key: 'phone', title: '联系方式', sortable: false },
  { key: 'registrationStatus', title: '报到状态', sortable: true },
  { key: 'paymentStatus', title: '缴费状态', sortable: true },
  { key: 'dormitory', title: '宿舍', sortable: false }
]

// 搜索筛选配置
const searchFilters = [
  {
    key: 'major',
    label: '专业',
    type: 'select',
    options: [
      { label: '计算机科学与技术', value: 'cs' },
      { label: '软件工程', value: 'se' },
      { label: '数据科学与大数据技术', value: 'ds' },
      { label: '人工智能', value: 'ai' },
      { label: '网络工程', value: 'ne' }
    ]
  },
  {
    key: 'registrationStatus',
    label: '报到状态',
    type: 'select',
    options: [
      { label: '已报到', value: 'completed' },
      { label: '报到中', value: 'in_progress' },
      { label: '待报到', value: 'pending' }
    ]
  },
  {
    key: 'paymentStatus',
    label: '缴费状态',
    type: 'select',
    options: [
      { label: '已缴费', value: 'paid' },
      { label: '未缴费', value: 'unpaid' },
      { label: '部分缴费', value: 'partial' }
    ]
  }
]

// 状态
const loading = ref(false)
const students = ref([])
const selectedRows = ref([])
const currentStudent = ref(null)

// 弹窗状态
const showAddModal = ref(false)
const showEditModal = ref(false)
const showDetailModal = ref(false)
const showImportModal = ref(false)

// 搜索参数
const searchParams = reactive({
  query: '',
  filters: {}
})

// 获取报到状态文本
const getRegistrationStatusText = (status) => {
  return getRegistrationStatus(status).text
}

// 获取缴费状态文本
const getPaymentStatusText = (status) => {
  return getPaymentStatus(status).text
}

// 处理搜索
const handleSearch = (params) => {
  searchParams.query = params.query
  searchParams.filters = params.filters
  loadStudents()
}

// 处理排序
const handleSort = (sortInfo) => {
  console.log('Sort:', sortInfo)
  // 实现排序逻辑
}

// 处理选择变化
const handleSelectionChange = (selectedIds) => {
  selectedRows.value = selectedIds
}

// 查看学生详情
const viewStudent = (student) => {
  currentStudent.value = student
  showDetailModal.value = true
}

// 编辑学生
const editStudent = (student) => {
  currentStudent.value = { ...student }
  showEditModal.value = true
}

// 删除学生
const deleteStudent = async (student) => {
  if (confirm(`确定要删除学生 ${student.name} 吗？`)) {
    try {
      await adminStore.deleteStudent(student.id)
      await loadStudents()
    } catch (error) {
      console.error('Delete student failed:', error)
    }
  }
}

// 关闭弹窗
const closeModal = () => {
  showAddModal.value = false
  showEditModal.value = false
  currentStudent.value = null
}

// 保存学生
const handleSaveStudent = async (studentData) => {
  try {
    await adminStore.saveStudent(studentData)
    closeModal()
    await loadStudents()
  } catch (error) {
    console.error('Save student failed:', error)
  }
}

// 批量导入
const handleImport = async (file) => {
  try {
    // 实现批量导入逻辑
    console.log('Import file:', file)
    showImportModal.value = false
    await loadStudents()
  } catch (error) {
    console.error('Import failed:', error)
  }
}

// 导出学生
const exportStudents = () => {
  // 实现导出逻辑
  console.log('Export students:', selectedRows.value)
}

// 处理登出
const handleLogout = () => {
  authStore.logout()
  router.push('/admin/login')
}

// 加载学生数据
const loadStudents = async () => {
  loading.value = true
  try {
    const result = await adminStore.fetchStudents(searchParams)
    students.value = result.data || []
  } catch (error) {
    console.error('Load students failed:', error)
  } finally {
    loading.value = false
  }
}

// 组件挂载时加载数据
onMounted(() => {
  loadStudents()
})

// 模拟组件（实际项目中应该单独创建文件）
const StudentModal = {
  template: `
    <div class="fixed inset-0 z-50 overflow-y-auto">
      <div class="flex items-center justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
        <div class="fixed inset-0 transition-opacity" @click="$emit('close')">
          <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
        </div>
        <div class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full">
          <div class="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
            <h3 class="text-lg font-medium text-gray-900 mb-4">
              {{ mode === 'add' ? '新增学生' : '编辑学生' }}
            </h3>
            <div class="space-y-4">
              <div>
                <label class="block text-sm font-medium text-gray-700">学号</label>
                <input v-model="form.studentId" type="text" class="input" placeholder="请输入学号">
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700">姓名</label>
                <input v-model="form.name" type="text" class="input" placeholder="请输入姓名">
              </div>
              <!-- 更多表单字段... -->
            </div>
          </div>
          <div class="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
            <button @click="handleSave" class="btn btn-primary sm:ml-3">
              {{ mode === 'add' ? '新增' : '保存' }}
            </button>
            <button @click="$emit('close')" class="btn btn-secondary">
              取消
            </button>
          </div>
        </div>
      </div>
    </div>
  `,
  props: ['visible', 'student', 'mode'],
  emits: ['close', 'save'],
  setup(props, { emit }) {
    const form = reactive({
      studentId: '',
      name: '',
      gender: '',
      major: '',
      class: '',
      phone: ''
    })
    
    const handleSave = () => {
      emit('save', form)
    }
    
    return { form, handleSave }
  }
}

const StudentDetailModal = {
  template: `
    <div class="fixed inset-0 z-50 overflow-y-auto">
      <div class="flex items-center justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
        <div class="fixed inset-0 transition-opacity" @click="$emit('close')">
          <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
        </div>
        <div class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-2xl sm:w-full">
          <div class="bg-white px-4 pt-5 pb-4 sm:p-6">
            <h3 class="text-lg font-medium text-gray-900 mb-4">学生详情</h3>
            <div class="grid grid-cols-2 gap-4">
              <div><strong>学号:</strong> {{ student?.studentId }}</div>
              <div><strong>姓名:</strong> {{ student?.name }}</div>
              <div><strong>性别:</strong> {{ student?.gender }}</div>
              <div><strong>专业:</strong> {{ student?.major }}</div>
              <!-- 更多详情字段... -->
            </div>
          </div>
          <div class="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
            <button @click="$emit('close')" class="btn btn-secondary">
              关闭
            </button>
          </div>
        </div>
      </div>
    </div>
  `,
  props: ['visible', 'student'],
  emits: ['close']
}

const ImportModal = {
  template: `
    <div class="fixed inset-0 z-50 overflow-y-auto">
      <div class="flex items-center justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
        <div class="fixed inset-0 transition-opacity" @click="$emit('close')">
          <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
        </div>
        <div class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full">
          <div class="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
            <h3 class="text-lg font-medium text-gray-900 mb-4">批量导入学生</h3>
            <div class="space-y-4">
              <div>
                <label class="block text-sm font-medium text-gray-700">选择Excel文件</label>
                <input @change="handleFileChange" type="file" accept=".xlsx,.xls" class="input">
              </div>
              <div class="text-sm text-gray-500">
                <p>支持格式：Excel (.xlsx, .xls)</p>
                <p>请确保文件包含：学号、姓名、性别、专业、班级等字段</p>
              </div>
            </div>
          </div>
          <div class="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
            <button @click="handleImport" class="btn btn-primary sm:ml-3" :disabled="!selectedFile">
              导入
            </button>
            <button @click="$emit('close')" class="btn btn-secondary">
              取消
            </button>
          </div>
        </div>
      </div>
    </div>
  `,
  props: ['visible'],
  emits: ['close', 'import'],
  setup(props, { emit }) {
    const selectedFile = ref(null)
    
    const handleFileChange = (event) => {
      selectedFile.value = event.target.files[0]
    }
    
    const handleImport = () => {
      if (selectedFile.value) {
        emit('import', selectedFile.value)
      }
    }
    
    return { selectedFile, handleFileChange, handleImport }
  }
}
</script>